package cn.tedu.csmall.passportbackup.config;

import cn.tedu.csmall.passportbackup.filter.JwtAuthorizationFilter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Slf4j
@Configuration
public class SecurityConfigration extends WebSecurityConfigurerAdapter {

    public SecurityConfigration() {
        log.debug("开始处理：SecurityConfigration");
    }

    @Bean
    public PasswordEncoder passwordEncoder(){
        log.debug("创建密码编码器：BCryptPasswordEncoder");
        return new BCryptPasswordEncoder();
    }

    @Bean
    @Override
    protected AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

    @Autowired
    private JwtAuthorizationFilter jwtAuthorizationFilter;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        String[] urls = {
                "/doc.html",
                "/swagger-resources/**",
                "/v2/api-docs",
                "/**/*.js",
                "/**/*.css",
                "/favicon.ico",
                "/admins/login",
        };

        http.authorizeRequests()  //要求请求必须被授权
        .antMatchers(urls)  //匹配一些路径
        .permitAll()  //允许访问
        .anyRequest()  //处理以上配置意以外的请求
        .authenticated();  //需要经过认证

        http.cors(); //允许跨域访问
        http.csrf().disable();  //禁止防止伪造跨域攻击

        http.addFilterBefore(jwtAuthorizationFilter, UsernamePasswordAuthenticationFilter.class);
    }
}
